package com.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test01 {

	/**
	 * @param args
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws IllegalArgumentException 
	 * @throws NoSuchFieldException 
	 */
	public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
		// TODO Auto-generated method stub
		Constructor cons = String.class.getConstructor(StringBuffer.class);
		String str1 = (String) cons.newInstance(new StringBuffer("Abc"));
		System.out.println(str1);
		
		Person p = new Person("dylan", 24);
		Field fieldAge = Person.class.getField("age");
		Field fieldName = Person.class.getDeclaredField("name");
		Field fieldMessage = Person.class.getDeclaredField("message");
		fieldName.setAccessible(true);
		fieldMessage.setAccessible(true);
		System.out.println("Name is " + fieldName.get(p));
		System.out.println("Age is " + fieldAge.get(p));
		System.out.println("Message is " + fieldMessage.get(p));
		changeBToX(p);
		System.out.println("--->after change<---");
		System.out.println("Name is " + fieldName.get(p));
		System.out.println("Age is " + fieldAge.get(p));
		System.out.println("Message is " + fieldMessage.get(p));
		Method charAt = String.class.getMethod("charAt", int.class);
		System.out.println(charAt.invoke(str1, 2));
		int[][][] a1 = new int[5][5][5];
		char[][] a2 = new char[5][5];
		System.out.println(a1.getClass().getName());
		System.out.println(a2.getClass().getName());
	}

	public static void changeBToX(Person p) throws IllegalArgumentException, IllegalAccessException {
		// TODO Auto-generated method stub
		Field[] fields = p.getClass().getFields();
		String str = "";
		for(Field temp : fields) {
			System.out.println("type = " + temp.getType());
			if(temp.getType() == String.class) {
				try{
					str = (String) temp.get(p);
					str = str.replace('b', 'x');
				} catch(Exception e) {
					temp.setAccessible(true);
					str = (String) temp.get(p);
					str = str.replace('b', 'x');
				}
				temp.set(p, str);
			}
		}
	}
	
}
